import React, { Component } from 'react'
import './index.less'
import api from '@MODULES/common/api'
import { Link, withRouter } from 'react-router-dom'
import store from 'store'
import Layout from '../../common/Layout'
import Header from '../../common/Header'
import Common from '../../common/Common'
import TabBar from '../../common/TabBar'
import PopUpBox from '../../common/PopUpBox'
import SwitchMask from '../../common/SwitchMask'
import axios from 'axios'
import QRCode from 'qrcode'





class Index extends Component {

    constructor(props) {
        super(props)
        var gridLayoutArr = [{
            title: "常用功能",
            dataArr: [{
                title: "1.推广海报",
                img: require("../../common/img/project/haibao_icon@2x.png"),
                to: '/share'
            },
            {
                title: "2.报名客户",
                img: require("../../common/img/project/baoming_icon@2x.png"),
                to: '/sign/up/customers'
            },
            {
                title: "3.逛店签到",
                img: require("../../common/img/project/guangdian_icon@2x.png"),
                to: () => {
                    api.poster({}, {
                        success: (data) => {
                            QRCode.toDataURL(data.data.url + '?act_id=' + store.get('active_id') + '&&friend_id=' + data.data.param.friend_id + '&&y_uid=' + data.data.param.y_uid + '&&url_path=/goShopping', { version: 6 })
                                .then(url => {
                                    this.setState({
                                        codeUrl: url,
                                        codeTitle: '逛店签到',
                                        code_type: 'codeImg'
                                    }, () => {
                                        this.PopUpBox.changeStatus()
                                    })
                                })
                                .catch(err => {
                                    console.error(err)
                                })
                        }
                    })
                }
            },
            {
                title: "4.直播邀请",
                img: require("../../common/img/project/zhibo_icon@2x.png"),
                to: () => {
                    this.props.history.push('/share/live')
                    api.getLive({}, {
                        success: (data) => {
                            QRCode.toDataURL(data.data.url, { version: 6 })
                                .then(url => {
                                    this.setState({
                                        codeUrl: url,
                                        code_type: 'codeImg'
                                    }, () => {
                                        this.PopUpBox.changeStatus()
                                    })
                                })
                                .catch(err => {
                                    console.error(err)
                                })
                        }
                    })
                }
            },
            {
                title: "5.线下签单",
                img: require("../../common/img/project/xianxia_icon@2x.png"),
                to: '/signature'
            },
            {
                title: "6.核销码",
                img: require("../../common/img/project/hexiao_icon@2x.png"),
                to: '/writeoffcode'
            },
            {
                title: "7.业主查询",
                img: require("../../common/img/project/chaxun_icon@2x.png"),
                to: '/ownerInquiry/searchUser'
            },
            {
                title: "8.奖励豆排行",
                img: require("../../common/img/project/paihang_icon@2x.png"),
                to: '/reward/bean/steak/line'
            },
            {
                title: "9.个人二维码",
                img: require("../../common/img/project/erweima_icon@2x.png"),
                to: '/personCode'
            },
            {
                title: "10.员工邀请",
                img: require("../../common/img/project/yaoqing_icon@2x.png"),
                to: () => {
                    api.invitationStaff({}, {
                        success: (data) => {
                            QRCode.toDataURL(data.data.url + '&&user_path=register', { version: 6 })
                                .then(url => {
                                    this.setState({
                                        codeUrl: url,
                                        codeTitle: '员工邀请',
                                        code_type: 'codeImg'
                                    }, () => {
                                        this.PopUpBox.changeStatus()
                                    })
                                })
                                .catch(err => {
                                    console.error(err)
                                })
                        }
                    })
                }
            },
            {
                title: "11.内购随身码",
                img: require("../../common/img/project/suishen_icon@2x.png"),
                to: '/hydraulic/engineer'
            },
            {
                title: "12.帮助中心",
                img: require("../../common/img/project/bangzhu_icon@2x.png"),
                to: '/help/center'
            }
            ]
        }, {
            title: '活动执行管理',
            dataArr: [
                {
                    title: "奖金池任务",
                    img: require("../../common/img/project/jiangjin_icon@2x.png"),
                    to: '/PrizePool'
                },
                {
                    title: "品牌惩罚任务",
                    img: require("../../common/img/project/chengfa_icon@2x.png"),
                    to: '/brandMission'
                },
                {
                    title: "手动奖励",
                    img: require("../../common/img/project/jiangli_icon@2x.png"),
                    to: '/brandMission/manual'
                },
                {
                    title: "目标分配",
                    img: require("../../common/img/project/distribution_icon@2x.png"),
                    to: '/distribution'
                },
                {
                    title: "活动费用充值",
                    img: require("../../common/img/project/chongzhi_icon@2x.png"),
                    to: '/activity/cost/recharge'
                },
                {
                    title: "注册审核",
                    img: require("../../common/img/project/zhuce_icon@2x.png"),
                    to: '/registrationReview'
                },
                {
                    title: "财务结算",
                    img: require("../../common/img/project/caiwu_icon@2x.png"),
                    to: '/financial/settlement'
                },
            ]
        }]
        this.state = {
            initialization: true,
            gridLayoutArr,
            switchMaskData: [],
            actId: '',
            userActiveInfo: {},
            activeName: '',
            code_type: '',
            code_text: '',
            code_url: '',
            rewardLlocationData: {},
            codeUrl: '',
            codeTitle: '',
            code_content: [],
            kpi_show_total: []
        }
    }

    componentDidMount() {
        // token,user_path,friend_id,act_id
        var pageUrlData = {
            token: Common.parseUrl(this.props.location.search, 'token'),
            user_path: Common.parseUrl(this.props.location.search, 'user_path'),
            friend_id: Common.parseUrl(this.props.location.search, 'friend_id'),
            act_id: Common.parseUrl(this.props.location.search, 'act_id'),
            data_url: Common.parseUrl(this.props.location.search, 'data_url'),
            y_uid: Common.parseUrl(this.props.location.search, 'y_uid'),
            url_path: Common.parseUrl(this.props.location.search, 'url_path'),
            carry_code: Common.parseUrl(this.props.location.search, 'carry_code'),
        }
        if (pageUrlData.data_url) {
            store.set('data_url', pageUrlData.data_url)
        }

        console.log(pageUrlData.url_path)
        if (pageUrlData.url_path) {

            switch (pageUrlData.url_path) {
                case '/engineer/bind/phone':
                    this.props.history.push(pageUrlData.url_path + '?carry_code=' + pageUrlData.carry_code)
                    break;
                case '/goShopping':
                    this.props.history.push(pageUrlData.url_path + '?y_uid=' + pageUrlData.y_uid)
                    break;
            }
        }


        console.log(pageUrlData)
        if (pageUrlData.token) {
            store.set('token', pageUrlData.token)
        }

        console.log(pageUrlData);

        if (pageUrlData.act_id) {
            store.set('active_id', pageUrlData.act_id)
        }

        this.setState({
            actId: store.get('active_id')
        }, () => {
            // api.wechatAppid({}, {
            //     success: (data) => {
            //         console.log(data);
            //     }
            // })
            // this.PopUpBox.changeStatus()
            // this.SwitchMask.changeStatus()
            api.getActivity({}, {
                success: (activeData) => {
                    console.log(activeData)
                    activeData.data.map(item => {
                        item.label = item.activity_name
                        item.value = item.act_id
                        if (item.value == this.state.actId) {
                            this.setState({
                                activeName: item.label
                            })
                        }
                    })
                    this.setState({
                        switchMaskData: activeData.data
                    })
                }
            })

            api.rewardLlocation({}, {
                success: (data) => {
                    this.setState({
                        rewardLlocationData: data.data
                    }, () => {
                        this.activeInfoUpData()
                    })
                }
            })
            // api.login({
            //     wx_openid: '4232cdsjbvisvbsb2',
            //     avatar: '3131',
            //     sex: '1',
            //     nickname: '2131222aa',
            //     unionid: '331231'
            // }, {
            //     success: (data) => {
            //         console.log(data)



            //         this.activeInfoUpData()
            //     }
            // })


            // this.PopUpBox.changeStatus()
            // this.SwitchMask.changeStatus()
        })

        // 政策弹窗
        api.getPolicy({}, {
            success: data => {
                if (!store.get('popup')) {
                    store.set('popup',true)
                    console.log(data)
                    var kpi_show_list = data.data.kpi_show_total.split("\n")
                    console.log(kpi_show_list)
                    this.setState({
                        code_content: kpi_show_list,
                        code_type: 'notice',
                    }, () => {
                        // this.SwitchMask.changeStatus()
                        this.PopUpBox.changeStatus()
                        
                    })
                }
            }
        })

    }
    componentWillUnmount() {
        clearTimeout(this.calcCountDownTime)
    }

    render() {
        return (
            <Layout>
                {
                    this.state.initialization ? <div id="main">
                        <Header leftContent={<div></div>}></Header>
                        {/* 顶部 */}
                        <div className="topContent">
                            {/* 活动切换 */}
                            <div className="activeSwitchBox">
                                <div className='title'>{this.state.activeName}</div>
                                <div className="switchBox" onClick={() => {
                                    this.SwitchMask.changeStatus()
                                }}>
                                    <span className="switchTitle">切换</span>
                                    <img className="switchImg" src={require('../../common/img/project/xiala_icon@2x.png')} alt="" />
                                </div>
                            </div>
                            {/* 用户信息 */}
                            <div className="userInfoBox">
                                <div className="userInfo">
                                    <div className="userFace" style={{
                                        backgroundImage: 'url(' + Common.showFace(this.state.userActiveInfo.user_head_img) + ')'
                                    }}></div>
                                    <div className="userDetailInfo">
                                        <div className="userName">{this.state.userActiveInfo.realname} 【{this.state.userActiveInfo.member_types_s}】</div>
                                        <div className="userTip">所属战队：{this.state.userActiveInfo.brands}</div>
                                        <div className="userTip">所属门店：{this.state.userActiveInfo.store}</div>
                                    </div>
                                </div>
                                <div className="userWalletBox">
                                    <div className="itemBox">
                                        <div className="title">{this.state.userActiveInfo.integral ? this.state.userActiveInfo.integral : '0'}</div>
                                        <div className="label">员工积分</div>
                                    </div>
                                    <div className="itemBox">
                                        <div className="title">{this.state.userActiveInfo.money ? this.state.userActiveInfo.money : '0'}</div>
                                        <div className="label">现金</div>
                                    </div>
                                    <div className="itemBox">
                                        <div className="title">{this.state.userActiveInfo.use_money ? this.state.userActiveInfo.use_money : '0'}</div>
                                        <div className="label">已提现金额</div>
                                    </div>
                                </div>
                            </div>
                            {
                                this.state.userActiveInfo.carryOutArr ? <div className="reminderBox fontZero">
                                    
                                    <div className="reminderInfo">
                                    <img className="reminderImg" src={require('../../common/img/project/tongzhi_icon@2x.png')} alt="" />
                                        <div className="title">距本阶段任务结束仅剩{this.state.endDay}天{this.state.endHours}时{this.state.endMinute}分{this.state.endSeconds}秒</div>
                                        <div className="label">您还差&nbsp;
                                        {
                                                this.state.userActiveInfo.carryOutArr.map((item, index) => {
                                                    return (item.value + item.label+'、')
                                                })
                                            }
                                            即可瓜分奖金</div>
                                    </div>
                                </div> : <div className="reminderBox fontZero">
                                        
                                        <div className="reminderInfo">
                                        <img className="reminderImg" src={require('../../common/img/project/tongzhi_icon@2x.png')} alt="" />
                                            {/* <div className="title">距本阶段任务结束仅剩{this.state.endDay}天{this.state.endHours}时{this.state.endMinute}分{this.state.endSeconds}秒</div> */}
                                            <div className="label">暂无阶段</div>
                                        </div>
                                    </div>
                            }
                        </div>
                        {/* 常用功能 */}
                        {
                            this.state.gridLayoutArr.map((item, index) => {
                                return <div className="gridLayoutBox" key={index}>
                                    <div className="gridTitle">{item.title}</div>
                                    <div className="gridBox">
                                        {
                                            item.dataArr.map((item2, index2) => {
                                                return <div className="itemBox" onClick={() => {
                                                    if (typeof item2.to === 'function') {
                                                        item2.to()
                                                    } else {
                                                        this.props.history.push(item2.to)
                                                    }
                                                }}>
                                                    <img className="itemImg" src={item2.img} alt="" />
                                                    <div className="itemTitle">{item2.title}</div>
                                                </div>
                                            })
                                        }
                                    </div>
                                </div>
                            })
                        }
                        <PopUpBox refs={(PopUpBox) => { this.PopUpBox = PopUpBox }} params={{
                            type: this.state.code_type,
                            codeUrl: this.state.codeUrl,
                            title: this.state.codeTitle,
                            content: this.state.code_content,
                        }} />

                        <SwitchMask refs={(SwitchMask) => { this.SwitchMask = SwitchMask }} params={{
                            type: 'radio',
                            title: '切换活动',
                            switchMaskData: this.state.switchMaskData,
                            onOk: (data) => {
                                // 得到的数据
                                console.log(data)
                                store.set('active_id', data[0].act_id)
                                this.setState({
                                    actId: data[0].act_id,
                                    activeName: data[0].activity_name
                                }, () => {
                                    console.log('actid', data[0].act_id)
                                    this.activeInfoUpData()
                                    this.pageJump(data[0].act_id)
                                })
                                // 切换弹出层的显示或隐藏
                                this.SwitchMask.changeStatus()
                            }
                        }} />

                        <TabBar content="index" />
                    </div> : ''
                }
            </Layout>
        )
    }

    activeInfoUpData = () => {
        api.getActUser({}, {
            success: (data) => {
                if (data.code === 502) {
                    this.props.history.push('/rewardPool')
                    return
                }
                if (data.code === 403) {
                    this.props.history.push('/register')
                    return
                }
                if (Object.prototype.toString.call(data.data.carry_out) === '[object Object]') {
                    var carryOutArr = []
                    for (const key in data.data.carry_out) {
                        carryOutArr.push({
                            key: key,
                            value: data.data.carry_out[key],
                            label: this.state.rewardLlocationData[key]
                        })
                    }
                    console.log()
                    data.data.carryOutArr = carryOutArr
                }
                this.setState({
                    userActiveInfo: data.data
                }, () => {
                    var new_dataArr = this.state.dataArr
                    new_dataArr
                })

                this.calcCountdown(data.data.end_time * 1000)
                store.set("userInfo", data.data)
            }
        })
    }

    pageJump = (actId) => {
        api.getloginurl({}, {
            success: data => {
                console.log(data.data + '?act_id=' + actId)
                store.remove('token')
                window.location.href = data.data + '?act_id=' + actId
            }
        })
    }


    // 倒计时
    calcCountdown = (endTimeDate) => {
        var timeNum = endTimeDate * 1
        var nowtime = new Date(),  //获取当前时间
            endtime = new Date(timeNum);  //定义结束时间
        console.log(endtime);
        var lefttime = endtime.getTime() - nowtime.getTime(),  //距离结束时间的毫秒数
            endDay = Math.floor(lefttime / (1000 * 60 * 60 * 24)),  //计算天数
            endHours = Math.floor(lefttime / (1000 * 60 * 60) % 24),  //计算小时数
            endMinute = Math.floor(lefttime / (1000 * 60) % 60),  //计算分钟数
            endSeconds = Math.floor(lefttime / 1000 % 60);  //计算秒数

        this.calcCountDownTime = setTimeout(() => {
            this.calcCountdown(timeNum)
        }, 1000)

        var params = {}
        params = {
            endDay,
            endHours,
            endMinute,
            endSeconds
        }
        // console.log(params);
        this.setState(params)
    }
}
export default withRouter(Index)